/**
 * 移动端权限路由守卫
 * 
 * 功能：
 * - 页面访问权限控制
 * - 动态路由拦截
 * - 权限不足时的重定向
 * 
 * @author Wu.Liang
 * @date 2025-01-30
 */

import { useAuthStore } from '@/store'
import { hasPagePermission } from '@/utils/menuPermission'

/**
 * 路由守卫配置
 */
const routeGuards = {
  // 不需要权限的白名单页面
  whiteList: [
    '/pages/login/login',
    '/pages/register/register',
    '/pages/error/404',
    '/pages/error/403'
  ],
  
  // 需要登录但不需要特定权限的页面
  authRequired: [
    '/pages/index/index',
    '/pages/services/services',
    '/pages/profile/index',
    '/pages/community-announcement/index',
    '/pages/community-announcement/detail',
    '/pages/activity-registration/index',
    '/pages/activity-registration/detail',
    '/pages/activity-registration/register',
    '/pages/convenience-service/index',
    '/pages/convenience-service/detail',
    '/pages/convenience-service/booking',
    '/pages/community-group-buying/index',
    '/pages/community-group-buying/detail',
    '/pages/community-group-buying/buy',
    '/pages/neighborly-mutual-aid/index',
    '/pages/neighborly-mutual-aid/detail',
    '/pages/neighborly-mutual-aid/publish',
    '/pages/lost-and-found/index',
    '/pages/lost-and-found/detail',
    '/pages/lost-and-found/publish',
    '/pages/second-hand-transaction/index',
    '/pages/second-hand-transaction/detail',
    '/pages/second-hand-transaction/publish',
    '/pages/more-services/index',
    '/pages/more-services/detail'
  ]
}

/**
 * 路由守卫类
 */
export class RouteGuard {
  constructor() {
    this.init()
  }

  /**
   * 初始化路由守卫
   */
  init() {
    // 拦截页面跳转
    uni.addInterceptor('navigateTo', {
      invoke: (args) => this.checkPermission(args),
      fail: (err) => this.handleError(err)
    })

    // 拦截重定向
    uni.addInterceptor('redirectTo', {
      invoke: (args) => this.checkPermission(args),
      fail: (err) => this.handleError(err)
    })

    // 拦截重新启动
    uni.addInterceptor('reLaunch', {
      invoke: (args) => this.checkPermission(args),
      fail: (err) => this.handleError(err)
    })

    // 拦截切换Tab
    uni.addInterceptor('switchTab', {
      invoke: (args) => this.checkPermission(args),
      fail: (err) => this.handleError(err)
    })
  }

  /**
   * 检查页面权限
   * @param {Object} args 路由参数
   * @returns {Object|false} 路由参数或false
   */
  checkPermission(args) {
    const url = args.url
    const path = this.extractPath(url)
    
    console.log('[路由守卫] 检查页面权限:', path)
    
    // 白名单页面直接放行
    if (routeGuards.whiteList.includes(path)) {
      console.log('[路由守卫] 白名单页面，直接放行:', path)
      return args
    }
    
    // 检查登录状态
    const authStore = useAuthStore()
    if (!authStore.isLoggedIn) {
      console.log('[路由守卫] 用户未登录，跳转到登录页')
      this.redirectToLogin()
      return false
    }
    
    // 暂时允许所有用户访问所有页面
    // TODO: 后续根据具体需求设置权限控制
    console.log('[路由守卫] 暂时允许访问所有页面:', path)
    
    console.log('[路由守卫] 权限检查通过:', path)
    return args
  }

  /**
   * 提取页面路径
   * @param {string} url 完整URL
   * @returns {string} 页面路径
   */
  extractPath(url) {
    // 移除查询参数
    const path = url.split('?')[0]
    return path
  }

  /**
   * 跳转到登录页
   */
  redirectToLogin() {
    uni.reLaunch({
      url: '/pages/login/login'
    })
  }

  /**
   * 跳转到403页面
   */
  redirectTo403() {
    uni.navigateTo({
      url: '/pages/error/403'
    })
  }

  /**
   * 处理路由错误
   * @param {Object} err 错误信息
   */
  handleError(err) {
    console.error('[路由守卫] 路由错误:', err)
  }

  /**
   * 检查当前页面权限
   * @param {string} path 页面路径
   * @returns {boolean} 是否有权限
   */
  checkCurrentPagePermission(path) {
    return hasPagePermission(path)
  }

  /**
   * 获取当前页面路径
   * @returns {string} 当前页面路径
   */
  getCurrentPagePath() {
    const pages = getCurrentPages()
    if (pages.length > 0) {
      const currentPage = pages[pages.length - 1]
      return '/' + currentPage.route
    }
    return ''
  }
}

/**
 * 创建路由守卫实例
 */
export const routeGuard = new RouteGuard()

/**
 * 页面权限检查工具函数
 */
export const checkPagePermission = (path) => {
  return routeGuard.checkCurrentPagePermission(path)
}

export const getCurrentPath = () => {
  return routeGuard.getCurrentPagePath()
}

export default routeGuard
